import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: localStorage.getItem('username') || '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
    localStorage.setItem('username', name)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username } = userInfo
    const token = 'admin-token'
    commit('SET_TOKEN', token)
    setToken(token)
    commit('SET_NAME', username)
  },

  // get user info
  getInfo({ commit, state }) {
    // commit('SET_NAME', 'admin')
  },

  // user logout
  logout({ commit, state }) {
    removeToken() // must remove  token  first
    resetRouter()
    commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

